<template>
    <div>
        <div ref="container" class="container">
            <div class="box">0</div>
        </div>
        <button @click="add">增加</button>
    </div>
</template>
<script>
import { ref } from 'vue'
export default {
    name: "XtxFlip",
    setup() {
        const container = ref(null)
        const num = ref(1)
        const addElement = () => {
            const div = document.createElement('div')
            div.setAttribute('class', 'box')
            div.innerHTML = num.value
            num.value++
            container.value.insertBefore(div, container.value.children[0])
        }

        //计算每个元素Start位置
        const First = () => {
            Array.prototype.map.call(container.value.children, (item => {
                const { x, y } = item.getBoundingClientRect()
                item._left = x
                item._top = y
            }))
        }
        //计算每个元素Last位置
        const Last = () => {
            Array.prototype.map.call(container.value.children, (item => {
                const { x, y } = item.getBoundingClientRect()
                if (item._left) {
                    const leftDis = item._left - x
                    const topDis = item._top - y
                    item.animate(
                        [{ transform: 'translate(' + leftDis + 'px,' + topDis + 'px)' }, { transform: '' }],
                        { duration: 1000 }
                    );
                }


            }))
        }

        const add = () => {
            First()
            addElement()
            Last()
        }
        return {
            container,
            add
        }
    }
}
</script>
<style lang="less" scoped>
.container {
    height: 500px;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;

    :deep(.box) {
        transition: all .8s;
        width: 50px;
        height: 50px;
        border-radius: 5px;
        background-color: skyblue;
        text-align: center;
        margin: 6px 5px;
        line-height: 50px;
    }
}
</style>